import os
import sys


FLAG_DEBUG = "debug"
FLAG_RELEASE = "release"
FLAG_RELEASE_WITH_GM_CMD = "release_with_gm_cmd"

def is_src_dir(filenames):
	for filename in filenames:
		if filename.endswith(".erl"):
			return True
	return False

def is_include_dir(filenames):
	for filename in filenames:
		if filename.endswith(".hrl"):
			return True
	return False

def get_dirs(path):
	src_dirs = []
	include_dirs = []
	for root, dirnames, filenames in os.walk(path):
		dirname = root.replace("\\", "/")
		if is_src_dir(filenames):
			src_dirs.append(dirname)
		if is_include_dir(filenames):
			include_dirs.append(dirname)
	return sorted(src_dirs), sorted(include_dirs)

def gen_content_str(src_dirs, include_dirs, build_flag):
	data = "{\n\t[\n"
	i = 0
	for dirname in src_dirs:
		if i < len(src_dirs)-1:
			data += "\t\t'%s/*',\n" % dirname
		else:
			data += "\t\t'%s/*'\n" % dirname
		i += 1
	data += "\t],\n"
	data += "\t[\n"
	data += "\t\tdebug_info,\n"
	for dirname in include_dirs:
		data += "\t\t{i, \"%s\"},\n" % dirname

	if build_flag == FLAG_DEBUG:
		data += "\t\t{d, debug},\n"	
		data += "\t\t{d, gm_cord},\n"
	elif build_flag == FLAG_RELEASE_WITH_GM_CMD:
		data += "\t\t{d, gm_cord},\n"

	data += "\t\t{outdir, \"ebin\"}\n"	
	data += "\t]\n}.\n"
	return data

def print_usage():
	data = """usage:python gen_emakefile.py [BUILD_FLAG]
BUILD_FLAG:debug|release|release_with_gm_cmd"""
	print (data)

def main():
	if len(sys.argv) <= 1:
		print_usage()
		sys.exit(1)
		return

	build_flag = sys.argv[1]
	if build_flag not in (FLAG_DEBUG, FLAG_RELEASE, FLAG_RELEASE_WITH_GM_CMD):
		print_usage()
		sys.exit(1)
		return

	dirs = get_dirs(".")
	src_dirs = dirs[0]
	include_dirs = dirs[1] 
	data = gen_content_str(src_dirs, include_dirs, build_flag)
	f = open("Emakefile", "w")
	f.write(data)
	f.close()

if __name__ == "__main__":
	main()
